package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.flow.util.FlowUpdateAuditUtil;
import com.softer.wxzj.common.flow.util.Result;
import com.softer.wxzj.common.logic.GenerateAccount;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseOwnerCommitteeService;
import com.softer.wxzj.service.ZoneCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 业委会
 *
 * @author wxr
 */
@Slf4j
@Service
public class BaseOwnerCommitteeServiceImpl implements BaseOwnerCommitteeService {
    @Autowired
    private BaseOwnerCommitteeMapper baseOwnerCommitteeMapper;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private ZoneCodeService zoneCodeService;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private Result result;
    @Autowired
    private ModifyUtil<BaseOwnerCommittee> modifyUtil;
    @Autowired
    private OperUtil operUtil;
    @Autowired
    private FlowUpdateAuditUtil flowUpdateAuditUtil;
    @Autowired
    private CombineEntityUtil<BaseOwnerCommittee> combineEntityUtil;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private OrgBankInfoMapper orgBankInfoMapper;
    @Autowired
    private BaseBankInfoMapper baseBankInfoMapper;
    @Autowired
    private DicContentMapper dicContentMapper;
    @Autowired
    private BaseOrganizationMapper baseOrganizationMapper;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private SysOperatorMapper sysOperatorMapper;
    @Autowired
    private FlowAuditdetailMapper flowAuditdetailMapper;
    @Autowired
    private GenerateAccount generateAccount;
    @Autowired
    private BaseOrganizationServiceImpl baseOrganizationService;

    /**
     * 查询业委会注册审核列表
     *
     * @param page
     * @param baseOwnerCommittee
     * @param flowType
     * @return
     */
    @Override
    public PageInfo<BaseOwnerCommittee> getAuditList(Page page, BaseOwnerCommittee baseOwnerCommittee, String flowType) {
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(flowType);
        List<BaseOwnerCommittee> list = new ArrayList<>();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (null != map) {
            //调用公用方法
            result.select(map, baseOwnerCommittee);
            list = baseOwnerCommitteeMapper.getListSubmit(baseOwnerCommittee);
        }
        PageInfo<BaseOwnerCommittee> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 业委会添加修改流
     *
     * @param businessId
     * @param opinion
     * @param mark
     * @return
     */
    @Override
    public CommonResult addAudit(String businessId, String opinion, String mark) {
        int i = NumberEnum.ONE.getNum();
        String auditState = flowAddAuditUtil.audit(businessId, opinion, mark, null);
        BaseOwnerCommittee baseOwnerCommittee = new BaseOwnerCommittee();
        baseOwnerCommittee.setId(businessId);
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
        baseOwnerCommittee.setRegDate(createdate);
        //审核条件封装在一个类中
        result.result(auditState, baseOwnerCommittee);
        //不在审核中则更新业务表
        if (null != auditState && !FlowStateEnum.IN_AUDIT.getState().equals(auditState)) {
            i = baseOwnerCommitteeMapper.update(baseOwnerCommittee);
        }
        return CommonResult.ResponseResult(i);
    }

    @Override
    public CommonResult updateAudit(String id, String opinion, String mark) {
        //注意区分id
        String businessId = baseModifyReqMapper.getBusinessId(id);
        int num = NumberEnum.ONE.getNum();
        String auditState = flowAddAuditUtil.audit(businessId, opinion, mark, null);
        //终审成功，修改业务表    其他状态不做处理
        if (FlowStateEnum.PASS.getState().equals(auditState)) {
            //将变更记录表字段更新至业务表
            Map<String, Object> map = modifyUtil.getMap(id);
            BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.getChangeColumn(map);
            num = baseOwnerCommitteeMapper.update(baseOwnerCommittee);
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 添加接口
     *
     * @param baseOwnerCommittee
     * @return
     */
    @Override
    public CommonResult insert(BaseOwnerCommittee baseOwnerCommittee) {
        return null;
    }

    /**
     * 保存并提交
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult submitAuditAndAdd(BaseOwnerCommittee baseOwnerCommittee) {
        CommonResult commonResult = insertToId(baseOwnerCommittee);
        if (commonResult.getData() == ShiroResultEnum.SUCCESS.getCode()) {
            CommonResult commonResult1 = insertSaveAndSubmit(commonResult.getId(),commonResult.getOperNo());
            if (commonResult1.getData() != ShiroResultEnum.SUCCESS.getCode()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "提交数据失败");
            }
        } else {
            return commonResult;

        }
        return commonResult;
    }

    /**
     * 提交
     */
    @Override
    public CommonResult insertSaveAndSubmit(String id,String operNo) {
        //调用增加方法
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.getInfo(id);
        baseOwnerCommittee.setFlowState(NumStrEnum.ONE.getNum());
        int flowNum = baseOwnerCommittee.getFlowNum() + 1;
        baseOwnerCommittee.setFlowNum(flowNum);
        int num = baseOwnerCommitteeMapper.update(baseOwnerCommittee);
        //若不失败，进入审批流
        //指定业务id和流程类型
        String initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.COMMITTEE_REGISTER.getType(), operNo);
        //判断返回值状态   当为2时更新业务表
        if (StringUtils.isNotBlank(initState)) {
            num = baseOwnerCommitteeMapper.updateFlowStateById(id, initState);
        }

        return CommonResult.ResponseResult(num);
    }

    /**
     * 只保存
     *
     * @param baseOwnerCommittee
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized CommonResult insertToId(BaseOwnerCommittee baseOwnerCommittee) {
        //查询该名是否可以使用ownerCommitteeName
        baseOwnerCommittee.setOwnerCommitteeName(baseOwnerCommittee.getOwnerCommitteeName().replace(" ", ""));
        //看看统一信用代码和名称有没有使用
        changeName(baseOwnerCommittee);
        List<String> list = Arrays.asList(baseOwnerCommittee.getRegionNo().split(","));
        String id = UUIDUtil.getUUID();
        baseOwnerCommittee.setId(id);
        BigInteger regNum;
        //生成账号
        BigInteger add = new BigInteger(NumStrEnum.ONE.getNum());
        String regNo = baseOwnerCommitteeMapper.selectMaxRegCode(baseOwnerCommittee.getOrgTypeCode());
        if (StringUtils.isBlank(regNo)) {
            regNo = NumStrEnum.ZERO.getNum();
            regNum = new BigInteger(regNo);
            String rNo = String.format("%09d", regNum);
            //业委会4开头
            if (("05").equals(baseOwnerCommittee.getOrgTypeCode())) {
                baseOwnerCommittee.setRegCode(NumStrEnum.FOUR.getNum() + rNo);
            } else {
                //居委会5开头
                baseOwnerCommittee.setRegCode(NumStrEnum.FIVE.getNum() + rNo);
            }
        } else {
            regNum = new BigInteger(regNo);
            regNum = regNum.add(add);
            String rNo = String.format("%09d", regNum);
            baseOwnerCommittee.setRegCode(rNo);
        }
        baseOwnerCommittee.setOrgName(baseOwnerCommittee.getOwnerCommitteeName());
        String operNo = generateAccount.generateAccount(baseOwnerCommittee.getOrgTypeCode());
        baseOrganizationService.createSysOperator(baseOwnerCommittee, id, operNo);
        //成立时间
        if (StringUtils.isEmpty(baseOwnerCommittee.getBuildDate())) {
            baseOwnerCommittee.setBuildDate(null);
        }
        //若前端不传数据则为审核状态则为保存0
        if (baseOwnerCommittee.getFlowState() == null || baseOwnerCommittee.getFlowState().isEmpty()) {
            baseOwnerCommittee.setFlowState(NumStrEnum.ZERO.getNum());
        } else if (String.valueOf(NumberEnum.TWO.getNum()).equals(baseOwnerCommittee.getFlowState())) {
            //获取String类型的时间
            baseOwnerCommittee.setFlowNum(1);
            baseOwnerCommittee.setRegDate(LocalDate.now().toString());
            flowUtil.saveDefaultFlowInstance(UUIDUtil.getUUID(), id, FlowTypeEnum.COMMITTEE_REGISTER.getType(), null, null);
        }
        //查看有没有共同的小区
        int num = 0;
        for (String s : list) {
            num = baseOwnerCommitteeMapper.selectRegionNo(baseOwnerCommittee.getOrgTypeCode(), s);
            if (num != 0) {
                return new CommonResult(0, "已经存在该小区");
            }
        }
        baseOwnerCommittee.setCreater(ShiroUserUtil.getUserName());
        num = baseOwnerCommitteeMapper.insertForId(baseOwnerCommittee);
        //保存图片
        CommonResult commonResult = fileService.addFile(baseOwnerCommittee.getFileTypeList(), baseOwnerCommittee.getId());
        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
        }
        return CommonResult.idResult(num, id, operNo);
    }

    /**
     * 测试修改变更时名字是否重复  1不能用   0可以用
     */
    private int changeName(BaseOwnerCommittee baseOwnerCommittee) {
        //查询变更是否有该数据
        //去空格
        baseOwnerCommittee.setOwnerCommitteeName(baseOwnerCommittee.getOwnerCommitteeName().replace(" ", ""));
        int num = NumberEnum.ZERO.getNum();
        num = baseModifyDetailMapper.selectCommitteName(baseOwnerCommittee.getOwnerCommitteeName());
        if (num > 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "名称已被使用");
        }
        if (StringUtils.isNotBlank(baseOwnerCommittee.getOrgCertificate())) {
            num = baseModifyDetailMapper.selectCommitteNum(baseOwnerCommittee.getOrgTypeCode());
            if (num > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "统一信用代码已被使用");
            }
            //查询现在修改的数据有没有这个名字，若有是不是这个id若是则不管他不是则返回重名
            BaseOwnerCommittee b = baseOwnerCommitteeMapper.findByNo(baseOwnerCommittee.getOrgCertificate());
            if (null != b) {
                if (!b.getId().equals(baseOwnerCommittee.getId())) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "名称已被使用");
                }
            }
            int no = baseOrganizationMapper.getCountByOrgCertificate(baseOwnerCommittee.getOrgCertificate());
            if (no > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "统一信用代码已被使用");
            }
        }
        //查询现在修改的数据有没有这个名字，若有是不是这个id若是则不管他不是则返回重名
        BaseOwnerCommittee b = baseOwnerCommitteeMapper.findByName(baseOwnerCommittee.getOwnerCommitteeName(), baseOwnerCommittee.getOrgTypeCode());
        if (null != b) {
            if (!b.getId().equals(baseOwnerCommittee.getId())) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "名称已被使用");
            }
        }
        return 0;
    }

    /**
     * 修改接口
     *
     * @param baseOwnerCommittee
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult update(BaseOwnerCommittee baseOwnerCommittee) {
        //去空格
        baseOwnerCommittee.setOwnerCommitteeName(baseOwnerCommittee.getOwnerCommitteeName().replace(" ", ""));
        int count = flowInstanceMapper.getCountByBusinessId(baseOwnerCommittee.getId());
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在审核中信息，不允许修改！");
        }
        //看名称是否可以使用
        int num = changeName(baseOwnerCommittee);
        if (num > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "该名称已经被使用，请重新输入");

        }
        BaseOwnerCommittee info = baseOwnerCommitteeMapper.getInfo(baseOwnerCommittee.getId());
        //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
        BaseOwnerCommittee ownerCommittee = combineEntityUtil.combineEntity(baseOwnerCommittee, info);
        int i = baseOwnerCommitteeMapper.updateById(ownerCommittee);
        //处理图片修改
        CommonResult result = fileService.updateFile(ownerCommittee.getFileTypeList(), ownerCommittee.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(i);
    }

    @Override
    public PageInfo<BaseModifyDetail> getModifyDetailList(Page page, BaseModifyDetail baseModifyDetail) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseModifyDetail> list = baseOwnerCommitteeMapper.getModifyDetailList(baseModifyDetail);
        //代码中文转换
        for (BaseModifyDetail modifyDetail : list) {
            switch (modifyDetail.getColumnName()) {
                case "regionNo":
                    String newRegionName = baseRegionInfoMapper.getRegionNameById(modifyDetail.getNewValue());
                    String oldRegionName = baseRegionInfoMapper.getRegionNameById(modifyDetail.getOldValue());
                    modifyDetail.setNewValue(null == newRegionName ? "" : newRegionName);
                    modifyDetail.setOldValue(null == oldRegionName ? "" : oldRegionName);
                    break;
                case "regionCode":
                    String newRegionCode = zoneCodeMapper.getZoneName(modifyDetail.getNewValue());
                    String oldRegionCode = zoneCodeMapper.getZoneName(modifyDetail.getOldValue());
                    modifyDetail.setNewValue(null == newRegionCode ? "" : newRegionCode);
                    modifyDetail.setOldValue(null == oldRegionCode ? "" : oldRegionCode);
                    break;
                case "bankId":
                    String newBankName = baseBankInfoMapper.getBankName(modifyDetail.getNewValue());
                    String oldBankName = baseBankInfoMapper.getBankName(modifyDetail.getOldValue());
                    modifyDetail.setNewValue(null == newBankName ? "" : newBankName);
                    modifyDetail.setOldValue(null == oldBankName ? "" : oldBankName);
                    break;
                case "certType":
                    String newCertName = dicContentMapper.selectName(modifyDetail.getNewValue());
                    String oldCertName = dicContentMapper.selectName(modifyDetail.getOldValue());
                    modifyDetail.setNewValue(null == newCertName ? "" : newCertName);
                    modifyDetail.setOldValue(null == oldCertName ? "" : oldCertName);
                    break;
                default:
                    break;
            }
            if (StringUtils.isNotBlank(modifyDetail.getCreater())) {
                String creater = sysOperatorMapper.selectAllName(modifyDetail.getCreater());
                modifyDetail.setCreater(creater);
            }
        }
        PageInfo<BaseModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 修改
     *
     * @param newBaseOwnerCommittee
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult updateToSave(BaseOwnerCommittee newBaseOwnerCommittee) throws Exception {
        //去空格
        String modifyType = newBaseOwnerCommittee.getModifyType();
        String modifyCause = newBaseOwnerCommittee.getModifyCause();
        newBaseOwnerCommittee.setOwnerCommitteeName(newBaseOwnerCommittee.getOwnerCommitteeName().replace(" ", ""));
        String id = newBaseOwnerCommittee.getId();
        //查询该名称是否可以使用
        int no = changeName(newBaseOwnerCommittee);
        if (no > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "该名称已被使用，请重修填写");
        }
        newBaseOwnerCommittee.setState(NumStrEnum.ONE.getNum());
        //获取原始业务数据
        BaseOwnerCommittee oldBaseOwnerCommittee = baseOwnerCommitteeMapper.getInfo(newBaseOwnerCommittee.getId());
        newBaseOwnerCommittee.setRegCode(oldBaseOwnerCommittee.getRegCode());
        newBaseOwnerCommittee.setState(oldBaseOwnerCommittee.getState());
        //变更类型表id    注意区分id!!
        String uuid = UUIDUtil.getUUID();
        //保存变更表
        int num = modifyUtil.updateToSave(oldBaseOwnerCommittee, newBaseOwnerCommittee, id, modifyType, modifyCause, uuid);
        if (NumberEnum.MINUS_ONE.getNum() == num) {
            num = 0;
        }
        // 图档变更操作
        int count = fileService.modifyFile(newBaseOwnerCommittee.getFileTypeList(), id, modifyType, modifyCause, uuid);
        if ((num + count) <= NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败");
        }
        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(id, uuid, modifyType, null);
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        CommonResult result = dealPassModify(initState, id, uuid);
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 处理变更审核通过的逻辑
     *
     * @param initState 审核状态
     * @param id        业务ID
     * @param uuid      变更ID
     * @return 处理结果
     */
    private CommonResult dealPassModify(String initState, String id, String uuid) {
        if (FlowStateEnum.PASS.getState().equals(initState)) {
            //查询数据库原数据
            BaseOwnerCommittee info = baseOwnerCommitteeMapper.getInfo(id);
            info.setFlowState(NumStrEnum.TWO.getNum());
            //变更值合并到原数据   注意参数：uuid变更类型id   info数据库实体
            BaseOwnerCommittee completeEntity = modifyUtil.getCompleteEntity(uuid, info);
            //全表更新
            int num = baseOwnerCommitteeMapper.updateById(completeEntity);
            if (num <= NumberEnum.ZERO.getNum()) {
                return CommonResult.ResponseResult(num);
            }
            //处理图档
            return fileService.dealPassModifyFile(uuid, id);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    @Override
    public CommonResult delete(String id) {
        int count = flowInstanceMapper.getCountByBusinessId(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在审核中信息，不允许删除！");
        }
        int req = orgBankInfoMapper.selectCountById(id);
        if (req > 0) {
            return CommonResult.ResponseResult(0, "已被使用无法删除");
        }
        int num = baseOwnerCommitteeMapper.delete(id);
        return CommonResult.ResponseResult(num);
    }

    /**
     * 查询要修改数据
     *
     * @param page
     * @param baseOwnerCommittee
     * @return
     */
    @Override
    public PageInfo<BaseOwnerCommittee> getList(Page page, BaseOwnerCommittee baseOwnerCommittee) {
        //赋值区域,重要
        baseOwnerCommittee.setZoneCode(operUtil.getZoneCode());
        //用于提交页面只能看到自己
        String flowState = ("0,3");
        //参数转换
        //setFuzzyParam(baseOwnerCommittee);
        if (flowState.equals(baseOwnerCommittee.getFlowState())) {
            baseOwnerCommittee.setCreater(ShiroUserUtil.getUserName());
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOwnerCommittee> list = baseOwnerCommitteeMapper.getList(baseOwnerCommittee);
        for (int i = 0; i < list.size(); i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf.parse(list.get(i).getCreateTime());
            } catch (ParseException e) {
                log.error("错误信息:()", e.getMessage(), e);
            }
            list.get(i).setCreateTime(sdf.format(date));
            //提取数值
            BaseOwnerCommittee b = list.get(i);
            //便利集合查询区县名称
            if (b.getRegionCode() != null) {
                b.setRegionCode(zoneCodeService.zoneCodeSuperiors(b.getRegionCode(), ShiroUserUtil.getUserName()));
            }
        }
        PageInfo<BaseOwnerCommittee> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public BaseOwnerCommittee getInfo(String id) {
        return null;
    }
    /**
     * 模糊参数转换赋值
     * @param baseOwnerCommittee
     */
    /*private void setFuzzyParam(BaseOwnerCommittee baseOwnerCommittee){
        if(null != baseOwnerCommittee && StringUtils.isNotBlank(baseOwnerCommittee.getFuzzyParam())){
            baseOwnerCommittee.setFuzzyParam(FuzzyConversionUtil.getFlowState(baseOwnerCommittee.getFuzzyParam()));
        }
    }*/

    /**
     * 查询单条数据
     *
     * @param id
     * @return
     */
    @Override
    public BaseOwnerCommittee getInfoById(String id, String arcType) {
        //查出要查的信息
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.getInfo(id);
        String superiors;
        SysOperator user = ShiroUserUtil.getUser();
        //查出该信息的上级所有区县代码
        if (NumStrEnum.ZERO.getNum().equals(user.getAddType())) {
            superiors = zoneCodeService.zoneCodeSuperiorsAll(baseOwnerCommittee.getRegionCode());
        } else {
            superiors = zoneCodeService.zoneCodeSuperiors(baseOwnerCommittee.getRegionCode(), ShiroUserUtil.getUserName());
        }
        //存储
        baseOwnerCommittee.setRegionCode(superiors);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        baseOwnerCommittee.setFileTypeList(fileVOList);
        return baseOwnerCommittee;
    }

    @Override
    public BaseOwnerCommittee rejectionExaminationApproval(String operNo, String arcType) {
        SysOperator sysOperator = sysOperatorMapper.selectName(operNo);
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.getInfo(sysOperator.getCompanyId());
        String superiors = zoneCodeService.zoneCodeSuperiorsAll(baseOwnerCommittee.getRegionCode());
        baseOwnerCommittee.setRegionCode(superiors);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(sysOperator.getCompanyId(), arcType);
        baseOwnerCommittee.setFileTypeList(fileVOList);
        //审核意见
        String opinion = flowAuditdetailMapper.getOpinion(baseOwnerCommittee.getId(), FlowTypeEnum.COMMITTEE_REGISTER.getType());
        //是不是在变更
        BaseModifyReq baseModifyReq = baseModifyReqMapper.selectFlowStateById(baseOwnerCommittee.getId(), "organization_modify");
        if (null != baseModifyReq) {
            baseOwnerCommittee.setUpdateFlowState(baseModifyReq.getFlowState());
        }
        baseOwnerCommittee.setOpinion(opinion);
        return baseOwnerCommittee;
    }

    /**
     * 获取外网确认变更接口
     *
     * @param modifyVO 变更项集合
     * @return 变更结果
     */
    @Override
    public CommonResult getExtraNetModify(ModifyVO modifyVO) {
        String uuid = UUIDUtil.getUUID();
        SysOperator sysOperator = sysOperatorMapper.selectName(modifyVO.getOperNo());
        String companyId = sysOperator.getCompanyId();
        //新增一条变更记录
        int num = modifyUtil.saveModifyReq(uuid, companyId, FlowTypeEnum.COMMITTEE_UPDATE.getType(), modifyVO.getModifyCause(), modifyVO.getOperNo());
        if (num == 0) {
            return CommonResult.ResponseResult(num, "新增变更记录失败");
        }
        //新增变更详情
        List<BaseModifyDetail> list = modifyVO.getList();
        baseOrganizationService.dealList(list, uuid, sysOperator.getOperName());
        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(companyId, uuid, FlowTypeEnum.COMMITTEE_UPDATE.getType(), modifyVO.getOperNo());
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        //终审成功，修改业务表    其他状态不做处理
        CommonResult result = dealPassModify(initState, companyId, uuid);
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(1);
    }

    /**
     * 外网获取变更信息列表
     *
     * @param page               分页信息
     * @param baseOwnerCommittee 查询信息
     * @return 业委会变更列表
     */
    @Override
    public PageInfo<BaseOwnerCommittee> getModifyListToExtraNet(Page page, BaseOwnerCommittee baseOwnerCommittee) {
        BaseOwnerCommittee org = getOrg(baseOwnerCommittee.getOperNo());
        baseOwnerCommittee.setId(org.getId());
        baseOwnerCommittee.setModifyType(FlowTypeEnum.COMMITTEE_UPDATE.getType());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOwnerCommittee> list = baseOwnerCommitteeMapper.getModifyListToExtraNet(baseOwnerCommittee);
        PageInfo<BaseOwnerCommittee> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 校验小区是否存在业委会或者居委会
     *
     * @param regionId 小区ID
     * @return true/false
     */
    @Override
    public Boolean checkRegion(String regionId) {
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.checkRegion(regionId);
        if (baseOwnerCommittee != null && StringUtils.isNotEmpty(baseOwnerCommittee.getId())) {
            return true;
        }
        return false;
    }

    /**
     * 查询业委会/居委会的小区列表
     *
     * @param page           分页信息
     * @param baseRegionInfo 查询实体
     * @return 小区列表
     */
    @Override
    public PageInfo<BaseRegionInfo> getOrgRegionList(Page page, BaseRegionInfo baseRegionInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseOwnerCommitteeMapper.getOrgRegionList(baseRegionInfo);
        return new PageInfo<>(list);
    }
    /**
     * 外网查询业委会/居委会管理的小区
     *
     * @param operNo 登录账号
     * @return 小区列表
     */
    @Override
    public List<BaseRegionInfo> getCommitteeRegionList(String operNo) {
        return baseOwnerCommitteeMapper.getCommitteeRegionList(operNo);
    }

    /**
     * 根据登录账号，查询业委会居委会信息
     *
     * @param operNo 登录账号
     * @return 业委会居委会信息
     */
    public BaseOwnerCommittee getOrg(String operNo) {
        SysOperator sysOperator = sysOperatorMapper.selectName(operNo);
        return baseOwnerCommitteeMapper.getInfo(sysOperator.getCompanyId());
    }

    /**
     * 业主居委会变更审核
     *
     * @param id      不是业务idr
     * @param opinion 意见
     * @param mark    同意/拒绝
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult changeResidentialCommittee(String id, String opinion, String mark) {
        //根据当前id 查询业务workId
        String workId = baseModifyReqMapper.getBusinessId(id);
        int num = NumberEnum.ZERO.getNum();
        String auditState = flowUpdateAuditUtil.audit(workId, opinion, mark);
        if (null != auditState) {
            num = NumberEnum.ONE.getNum();
            //终审成功，修改业务表    其他状态不做处理
            CommonResult result = dealPassModify(auditState, workId, id);
            if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
            }
        }
        return CommonResult.ResponseResult(num);
    }
/**
 * 外网修改并提交
 */
    /**
     * @param baseOwnerCommittee
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateAndAdd(BaseOwnerCommittee baseOwnerCommittee) {
        CommonResult commonResult = update(baseOwnerCommittee);
        if (commonResult.getData() == ShiroResultEnum.SUCCESS.getCode()) {
            CommonResult commonResult1 = insertSaveAndSubmit(baseOwnerCommittee.getId(),baseOwnerCommittee.getOperNo());
            if (commonResult1.getData() != ShiroResultEnum.SUCCESS.getCode()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "提交审核失败");
            }
        } else {
            return commonResult;
        }
        return commonResult;
    }

    /**
     * 备案
     *
     * @param baseOwnerCommittee recDate备案时间now
     *                           state 备案1 撤销备案0
     * @return
     */
    @Override
    public CommonResult record(BaseOwnerCommittee baseOwnerCommittee) {
        int num = 0;
        //将变更记录表字段更新至业务表
        num = baseOwnerCommitteeMapper.record(baseOwnerCommittee);
        return CommonResult.ResponseResult(num);

    }

    /**
     * 查看登录人有没有这个权限
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult selectWhoLogin(String id) {
        BaseOwnerCommittee baseOwnerCommittee = baseOwnerCommitteeMapper.getInfo(id);
        if (baseOwnerCommittee.getCreater().equals(ShiroUserUtil.getUserName())) {
            return CommonResult.ResponseResult(1);
        }
        return new CommonResult(0, "抱歉您没有权限编辑此信息");
    }
}

